package com.skillworld.webapp.model.bag;

import java.util.Calendar;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;

import com.skillworld.webapp.model.item.Item;

@Entity
@Table(name="ItemRecord")
public class ItemRecord implements Cloneable
{
	private Long recordId;
	private Item item;
	private int usesLeft;
	private Calendar expirationDate = null;
	private Bag bag = null;

	
	protected ItemRecord() 
	{

	}

    public ItemRecord(Item item)
    {
        this.item = item;
        this.usesLeft = item.getUses();
    }     
    
	public ItemRecord(Item item, Calendar expirationDate)
	{
		this.item = item;
		this.usesLeft = item.getUses();
		this.expirationDate = expirationDate;
	}
	
	public ItemRecord(Item item, Bag inv)
    {
        this.item = item;
        this.bag = inv;
        this.usesLeft = item.getUses();
        
    }


	@SequenceGenerator(name="ItemRecordIdGenerator",sequenceName="ItemRecordSeq")
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO,generator="ItemRecordIdGenerator")
	@Column(name="idRecord")
	public Long getRecordId() {
		return recordId;
	}

	public void setRecordId(Long recordId) {
		this.recordId = recordId;
	}

	@ManyToOne(optional=false,fetch=FetchType.LAZY)
	@JoinColumn(name="idItem")
	public Item getItem() {
		return item;
	}

	public void setItem(Item item) {
		this.item = item;
	}

	@Column(name="usesLeft")
	public int getUsesLeft() {
		return usesLeft;
	}

	public void setUsesLeft(int usesLeft) {
		this.usesLeft = usesLeft;
	}

	@Temporal(TemporalType.DATE)
	@Column(name="expirationDate")
	public Calendar getExpirationDate() {
		return expirationDate;
	}

	public void setExpirationDate(Calendar expirationDate) {
		this.expirationDate = expirationDate;
	}
	
	@Transient
	public boolean isExpired()
	{
	    return (getExpirationDate() != null)
	            && Calendar.getInstance().after(getExpirationDate());
	}

    @ManyToOne(optional=false,fetch=FetchType.LAZY)
    @JoinColumn(name="idInventory")
    public Bag getBag() {
        return bag;
    }

    public void setBag(Bag bag) {
        this.bag = bag;
    }
    
    public void consume()
    { 
        usesLeft--;
    }
    
    @Override
    public ItemRecord clone()
    { 
        ItemRecord newEntry = new ItemRecord();
        newEntry.setItem(getItem());
        newEntry.setUsesLeft(getUsesLeft());
        newEntry.setExpirationDate(getExpirationDate());
        
        return newEntry;
    }
	
}
